﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Giraffe.Client.Common;
using Giraffe.Core.Common.Messengers;
using Giraffe.Core.Model;

namespace Giraffe.Client.ConversationModule.History
{
    public class ConversationHistoryVM: ViewModelBase
    {
        private readonly IConversation _conversation;
        private ObservableCollection<MessageVM> _messages;

        public ConversationHistoryVM(IConversation conversation)
        {
            _conversation = conversation;
            _messages = new ObservableCollection<MessageVM>();
            _conversation.MessagesUpdated += OnMessagesUpdated;

            UpdateMessages();
        }

        private void OnMessagesUpdated()
        {
            UpdateMessages();
        }

        public ObservableCollection<MessageVM> Messages
        {
            get
            {
                return _messages;
            }
        }

        private void UpdateMessages()
        {
            if (!base.Dispatcher.CheckAccess())
            {
                base.Dispatcher.Invoke((Action)UpdateMessages);
                return;
            }

            //todo update only new and old
            _messages.Clear();
            foreach (IMessage iMessage in _conversation.Messages)
            {
                _messages.Add(new MessageVM(iMessage));
            }
        }
    }
}